package cn.bdqn.controller;

import cn.bdqn.bean.httputil.HttpRequest;
import cn.bdqn.domain.Departments;
import cn.bdqn.domain.User;
import cn.bdqn.service.DepartmentsService;
import cn.bdqn.service.UserService;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @Author 周安康
 * @create 2020/10/3 10:23
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private DepartmentsService departmentsService;

    /**
     * 登录
     * @param code 微信code
     * @param session   session
     * @return
     */
    @PostMapping("/login")
    public Map gettingOpenID(@RequestParam("code") String code, HttpSession session){
        Map map = new HashMap();
        //登录凭证不能为空
        if (code == null || code.length() == 0) {
            map.put("status", 0);
            map.put("msg", "code 不能为空");
            return map;
        }
        //小程序唯一标识   (在微信小程序管理后台获取)
        String wxspAppid = "wxce82b7de4408ff94";
        //小程序的 app secret (在微信小程序管理后台获取)
        String wxspSecret = "db560d6d403b4007d414675bdbd95db9";
        //授权（必填）
        String grant_type = "authorization_code";

        //1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid
        //请求参数
        String params = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" + code + "&grant_type=" + grant_type;
        //发送请求
        String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
        //解析相应内容（转换成json对象）
        JSONObject json = JSONObject.fromObject(sr);
        //用户的唯一标识（openid）
        String openid = (String) json.get("openid");

        //自定义变量表示数据库是否有这个用户  true:有    false:没有
        boolean a = true;
        User userInfo = userService.queryUserByOpenID(openid);
        if (userInfo == null){
            a = false;
        }else{
            session.setAttribute("userId",userInfo.getId());
        }
        // 第三步、计划返回结果集
        if (sr.contains("errcode")){
            map.put("status",500);
            return map;
        }
        //获取sessionId
        String sessionId = session.getId();

        ServletContext sc = session.getServletContext();
        sc.setAttribute("userSession",sessionId);
        map.put("status",200);
        map.put("ticket", UUID.randomUUID());
        map.put("openId",openid);
        map.put("userInfo",userInfo);
        map.put("userSession",sessionId);
        map.put("a",a);
        System.out.println(openid);
        return map;
    }

    @RequestMapping("/register")
    @ResponseBody
    public Map<String,Object> register(String openId,String headImgUrl,String nickName,Integer sex){

        //接收小程序传来的参数
        User user = new User(openId,headImgUrl,nickName,sex);

        int result = userService.addUser(user);
        Map<String,Object> resultMap = new HashMap<String,Object>();
        resultMap.put("addStatus",result);
        resultMap.put("userInfo",user);

        return resultMap;
    }

    @RequestMapping("/getUser")
    @ResponseBody
    public Map<String,Object> getUserByOpenId(String openId) {
        System.out.println(openId + ":openId");

        User userInfo = userService.queryUserByOpenID(openId);

        Map<String,Object> resultMap = new HashMap<String,Object>();
        resultMap.put("userInfo",userInfo);

        return resultMap;
    }

    /**
     * 根据小程序传来的值修改添加用户信息
     * @param openid
     * @param userName
     * @param phone
     * @param idCard
     * @param area
     * @return
     */
    @RequestMapping("/amend")
    @ResponseBody
    public Map<String,Object> amendUserInfo(String openid,String userName,String phone,String idCard,String area,Integer status){

        //接收小程序传来的参数
        User user = new User(openid,userName,phone,idCard,area,status);

        int result = userService.updateUserByOpenId(user);
        Map<String,Object> resultMap = new HashMap<String,Object>();
        resultMap.put("updateStatus",result);

        return resultMap;
    }

    /**
     * 根据用户的openId查询其就诊信息状态
     * @param openid 小程序传来的openid。注意 需要和小程序中的一致
     * @return
     */
    @RequestMapping("/queryStatus")
    @ResponseBody
    public Map<String,Object> queryStatus(String openid){

        System.out.println("走了没？");

        int result = userService.selectStatusByOpenId(openid);

        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("infoStatus",result);

        return resultMap;
    }

    /**
     * 查询所有科室信息
     * @return
     */
    @RequestMapping("/showDepartmentsInfo")
    @ResponseBody
    public Map<String,Object> showAllInfo(){

        List<Departments> departments = departmentsService.selectAllInfo();

        Map<String,Object> resultMap = new HashMap<String,Object>();
        resultMap.put("showInfo",departments);

        return resultMap;
    }


}
